<?php

/**
 * Class that represent a row in a table in database
 */
abstract class basemodel {

    /**
     * Table where fields values are stocked
     */
    protected $data = array();

    /**
     * Create a row in database
     * @param type $row Array of fields value
     */
    public function __construct($row = array()) {
        foreach ($row as $nom => $valeur) {
            $this->__set($nom, $valeur);
        }
    }

    /**
     * Set field value
     * @param type $nom
     * @param type $valeur 
     */
    public function __set($nom, $valeur) {
        $this->data[$nom] = $valeur;
    }

    /**
     * Get field value
     * @param type $nom
     * @return type 
     */
    public function __get($nom) {
        return htmlspecialchars($this->data[$nom]);
    }

    /**
     * Save the row in database
     * @return type 
     */
    public function save() {
        $connection = new dbconnection();

        if ($this->id) {
            $sql = "update " . get_class($this) . " set ";

            $set = array();
            foreach ($this->data as $att => $value)
                if ($att != 'id' && $value)
                    $set[] = "$att = '" . $value . "'";

            $sql .= implode(",", $set);
            $sql .= " where id=" . $this->id;
        }
        else {
            $sql = "insert into " . get_class($this) . " ";
            $sql .= "(" . implode(",", array_keys($this->data)) . ") ";
            $sql .= "values ('" . implode("','", array_values($this->data)) . "')";
        }
        $connection->doExec($sql);
        $id = $connection->getLastInsertId(get_class($this));

        return $id == false ? NULL : $id;
    }

}
